package com.wsz.common.utils;

import io.jsonwebtoken.*;
//帮助类
import java.util.Date;
public class JwtUtil {

    /**
     * 生成JSON Web令牌的工具类
     */
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    private static String tokenSignKey = "123456";

        public static String createToken(String userId, String username) {
            String token = Jwts.builder()
                    .setSubject("AUTH-USER")
                    //有效时间
                    .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                    .claim("userId", userId)
                    .claim("username", username)
                    //更具密钥进行加密
                    .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                    //密钥压缩到一行
                    .compressWith(CompressionCodecs.GZIP)
                    .compact();
            return token;
        }

        public static String getUserId(String token) {
            try {
                if (token == null || token.length() == 0) return null;

                Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
                Claims claims = claimsJws.getBody();
                return (String) claims.get("userId");
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        public static String getUsername(String token) {
            try {

                if (token == null || token.length() == 0) return "";
                Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
                Claims claims = claimsJws.getBody();
                return (String) claims.get("username");
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        public static void removeToken(String token) {
            //jwttoken无需删除，客户端扔掉即可。
        }

    public static void main(String[] args) {
        String wsz = JwtUtil.createToken("1", "admin");
        System.out.println(wsz);System.out.println(JwtUtil.getUsername(wsz));
        System.out.println(JwtUtil.getUserId(wsz));

    }
}

